import 'package:flutter/material.dart';
import 'package:flutter_baselib/lib.dart';
import 'package:flutter_baselib/src/config/toast_config.dart';
import 'package:fluttertoast/fluttertoast.dart';

import 'log_utils.dart';

///toast工具
class ToastUtils {
  ToastUtils._();

  static String _tag = 'ToastUtils';
  static bool _isFirst = true;
  static ToastConfig _toastConfig = ToastConfig.obtain(
    fontSize: 16,
    gravity: ToastGravity.BOTTOM,
    backgroundColor: Colors.black87,
    textColor: Colors.white,
  );

  ///初始化Toast
  static void init(ToastConfig toastConfig) {
    if (toastConfig != null) {
      _toastConfig = toastConfig;
    }
  }

  ///显示Toast
  static void show(String text, {bool isShowLong = false, ToastConfig toastConfig}) {
    if (text != null && text.length > 0) {
      if (_isFirst) {
        _isFirst = false;
      } else {
        Fluttertoast.cancel();
      }

      toastConfig ??= _toastConfig;

      Fluttertoast.showToast(
        msg: text,
        toastLength: isShowLong ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT,
        gravity: toastConfig.gravity ?? _toastConfig.gravity,
        backgroundColor: toastConfig.backgroundColor ?? _toastConfig.backgroundColor,
        textColor: toastConfig.textColor ?? _toastConfig.textColor,
        fontSize: toastConfig.fontSize ?? _toastConfig.fontSize,
      );
      LogUtils.i(_tag, '用户可见的Toast Text:$text');
    } else {
      LogUtils.w(_tag, "toast content is empty");
    }
  }

  ///仅在测试环境显示的Toast,方便调测用的
  static void showDebug(String text) {
    if (BaseLibPlugin.isDebug) {
      if (text != null && text.length > 0) {
        if (_isFirst) {
          _isFirst = false;
        } else {
          Fluttertoast.cancel();
        }

        Fluttertoast.showToast(
          msg: text,
          toastLength: Toast.LENGTH_LONG,
          gravity: ToastGravity.CENTER,
          backgroundColor: Colors.red,
          textColor: Colors.white,
          fontSize: 16,
        );
      } else {
        LogUtils.w(_tag, "showDebug toast content is empty");
      }
    }
  }
}
